class Solution(object):
    def orangesRotting(self, grid):
        m = len(grid)
        n = len(grid[0])
        dist = 0
        now_fresh = set()
        now_unfresh = set()
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 2:
                    now_unfresh.add((i, j))
                if grid[i][j] == 1:
                    now_fresh.add((i, j))
        while now_fresh and now_unfresh:
            dist += 1
            next_unfresh = set()
            for x, y in now_unfresh:
                for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                    if 0 <= ux < m and 0 <= uy < n and grid[ux][uy] == 1:
                        grid[ux][uy] = 2
                        next_unfresh.add((ux, uy))
                        now_fresh.remove((ux, uy))
            now_unfresh = next_unfresh
        if not now_fresh:
            return dist
        else:
            return -1






data = Solution()
grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]
print(data.orangesRotting(grid))
